package com.sz.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.vo.JsonResult;
import com.diboot.iam.entity.IamUser;
import com.diboot.iam.mapper.IamUserMapper;
import com.diboot.iam.util.IamSecurityUtils;
import com.sz.mes.dto.InstockDTO;
import com.sz.mes.entity.*;
import com.sz.mes.entity.warehouse.*;
import com.sz.mes.mapper.*;
import com.sz.mes.mapper.warehouse.*;
import com.sz.mes.service.InstockService;
import com.sz.mes.service.impl.BaseCustomServiceImpl;
import com.sz.mes.service.warehouse.LatticeService;
import com.sz.mes.vo.InstockDetailVO;
import com.sz.mes.vo.ShelfIdAndGoodQuantityVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.hibernate.validator.constraints.Length;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.Max;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 入库相关Service实现
 *
 * @author hem
 * @version 1.0
 * @date 2023-05-25
 * Copyright © szhs
 */
@Service
@Slf4j
public class InstockServiceImpl extends BaseCustomServiceImpl<InstockMapper, Instock> implements InstockService {

    private final InstockMapper instockMapper;
    private final LatticeMapper latticeMapper;
    private final LatticeService latticeService;
    private final ShelvesMapper shelvesMapper;
    private final AreaMapper areaMapper;
    private final WarehouseMapper warehouseMapper;
    private final LatticeGoodsMapper latticeGoodsMapper;
    private final InstockLatticeMapper instockLatticeMapper;
    private final InstockRecordMapper instockRecordMapper;
    private final GoodsMapper goodsMapper;
    private final IamUserMapper iamUserMapper;
    private final ProductTaskMapper productTaskMapper;
    private final PurchaseOrderMapper purchaseOrderMapper;
    private final ReceivementMapper receivementMapper;
    private final CompleteRptMapper completeRptMapper;
    private final ZhCnMapper zhCnMapper;

    public InstockServiceImpl(InstockMapper instockMapper, LatticeMapper latticeMapper, LatticeService latticeService,
                              ShelvesMapper shelvesMapper, AreaMapper areaMapper, WarehouseMapper warehouseMapper,
                              LatticeGoodsMapper latticeGoodsMapper, InstockLatticeMapper instockLatticeMapper,
                              InstockRecordMapper instockRecordMapper, GoodsMapper goodsMapper, IamUserMapper iamUserMapper,
                              ProductTaskMapper productTaskMapper, PurchaseOrderMapper purchaseOrderMapper,
                              ReceivementMapper receivementMapper, CompleteRptMapper completeRptMapper,
                              ZhCnMapper zhCnMapper) {
        this.instockMapper = instockMapper;
        this.latticeMapper = latticeMapper;
        this.latticeService = latticeService;
        this.shelvesMapper = shelvesMapper;
        this.areaMapper = areaMapper;
        this.warehouseMapper = warehouseMapper;
        this.latticeGoodsMapper = latticeGoodsMapper;
        this.instockLatticeMapper = instockLatticeMapper;
        this.instockRecordMapper = instockRecordMapper;
        this.goodsMapper = goodsMapper;
        this.iamUserMapper = iamUserMapper;
        this.productTaskMapper = productTaskMapper;
        this.purchaseOrderMapper = purchaseOrderMapper;
        this.receivementMapper = receivementMapper;
        this.completeRptMapper = completeRptMapper;
        this.zhCnMapper = zhCnMapper;
    }

    private Instock findByAcceptanceNum(String acceptanceNum) {
        QueryWrapper<Instock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("acceptance_num", acceptanceNum);
        queryWrapper.eq("is_deleted", 0);
        return instockMapper.selectOne(queryWrapper);
    }

    @Override
    public JsonResult insertInstock(InstockDTO instock) {
        Instock instockFromDB = this.findByAcceptanceNum(instock.getAcceptanceNum());
//        if (instockFromDB != null) {
//            if (instock.getId() == null) {
//                return JsonResult.FAIL_OPERATION("新增入库单失败, 入库单号已存在");
//            }
//            if (instock.getId() != null && !instockFromDB.getId().equals(instock.getId())) {
//                return JsonResult.FAIL_OPERATION("更新入库单失败, 入库单号已存在");
//            }
//        }
        if (instockFromDB != null ){
            return JsonResult.FAIL_OPERATION("新增入库单失败, 入库单号已存在");
        }else {
            Long currentUserId = IamSecurityUtils.getCurrentUserId();
            IamUser iamUser = iamUserMapper.selectById(currentUserId);
            instock.setCreateBy(iamUser.getRealname());
//            instock.setUpdateBy(iamUser.getRealname());
            instockMapper.insert(instock);

            //扫码时检查库位是否已被删除或是扫描出来的是其它环境的库位id
            if (!CollectionUtils.isEmpty(instock.getShelfIdAndGoodsQuantityVOList().get(0).getShelfName())
                    && instock.getShelfIdAndGoodsQuantityVOList().get(0).getLatticeId() != null) {
                for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : instock.getShelfIdAndGoodsQuantityVOList()) {
                    Lattice lattice = latticeService.findById(shelfIdAndGoodQuantityVO.getLatticeId());
                    if (lattice == null) {
                        return JsonResult.FAIL_NOT_FOUND("二维码对应的库位存在异常");
                    }
                }
            }
            //新增入库单
            if (!CollectionUtils.isEmpty(instock.getShelfIdAndGoodsQuantityVOList().get(0).getShelfName())
                    && instock.getShelfIdAndGoodsQuantityVOList().get(0).getLatticeId() != null) {
                for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : instock.getShelfIdAndGoodsQuantityVOList()) {
                    Lattice lattice = latticeService.findById(shelfIdAndGoodQuantityVO.getLatticeId());
                    instock.setLabel(lattice.getLabel());
                }
            }


            Integer allQuantity = 0;
            if (!CollectionUtils.isEmpty(instock.getShelfIdAndGoodsQuantityVOList().get(0).getShelfName())
                    && instock.getShelfIdAndGoodsQuantityVOList().get(0).getLatticeId() != null) {
                for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : instock.getShelfIdAndGoodsQuantityVOList()) {
                    allQuantity += shelfIdAndGoodQuantityVO.getQuantity();
                    Lattice lattice = latticeService.findById(shelfIdAndGoodQuantityVO.getLatticeId());
                    //货格如果是空仓就设置为空闲
                    if (lattice.getStatus() == 2) {
                        lattice.setStatus(0);
                        latticeMapper.updateById(lattice);
                    }
                    //货架如果是空仓就设置为空闲
                    Shelves shelves = shelvesMapper.selectById(lattice.getWarehouseShelvesId());
                    if (shelves.getStatus() == 2) {
                        shelves.setStatus(0);
                        shelvesMapper.updateById(shelves);
                    }
                    //货区如果是空仓就设置为空闲
                    Area area = areaMapper.selectById(shelves.getWarehouseAreaId());
                    if (area.getStatus() == 2) {
                        area.setStatus(0);
                        areaMapper.updateById(area);
                    }
                    //仓库如果是空仓就设置为空闲
                    Warehouse warehouse = warehouseMapper.selectById(area.getWarehouseId());
                    if (warehouse.getStatus() == 2) {
                        warehouse.setStatus(0);
                        warehouseMapper.updateById(warehouse);
                    }

                    //更新入库表
                    QueryWrapper<Instock> instockQueryWrapper = new QueryWrapper<>();
                    instockQueryWrapper.eq("acceptance_num", instock.getAcceptanceNum());
                    instock.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                    instockMapper.update(instock, instockQueryWrapper);

                    //新增入库货格表
                    InstockLattice instockLattice = new InstockLattice();
                    instockLattice.setInstockId(instock.getId());
                    instockLattice.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                    instockLattice.setWarehouseLatticeId(shelfIdAndGoodQuantityVO.getLatticeId());
                    instockLattice.setLabel(lattice.getLabel());
                    instockLattice.setGoodsId(instock.getGoodsId());
                    instockLatticeMapper.insert(instockLattice);
                    //入库操作记录
                    InstockRecord instockRecord = new InstockRecord();
                    instockRecord.setInstockId(instock.getId());
                    instockRecord.setGoodsId(instock.getGoodsId());
                    instockRecord.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                    instockRecord.setWarehouseLatticeId(shelfIdAndGoodQuantityVO.getLatticeId());
                    instockRecord.setType(instock.getReceiptType());
                    instockRecordMapper.insert(instockRecord);
                    //货格关联商品表（库存数量表更新）
                    QueryWrapper<LatticeGoods> wrapper = new QueryWrapper<>();
                    wrapper.eq("goods_id", instock.getGoodsId());
                    wrapper.eq("warehouse_lattice_id", shelfIdAndGoodQuantityVO.getLatticeId());
                    LatticeGoods latticeGoods = latticeGoodsMapper.selectOne(wrapper);
                    //查询商品表，得到商品名称、商品编号、商品规格
                    //            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
                    //            goodsQueryWrapper.eq("id", instock.getGoodsId());
                    //            Goods goods = goodsMapper.selectOne(goodsQueryWrapper);
                    Integer productTaskQuantity = 0;
                    Integer warehouseQuantity = 0;
                    if (instock.getReceiptType().equals("SCRK")) {
                        CompleteRpt completeRpt = new CompleteRpt();

                        Integer quantity = shelfIdAndGoodQuantityVO.getQuantity();
                        QueryWrapper<ProductTask> productTaskQueryWrapper = new QueryWrapper<>();
                        productTaskQueryWrapper.eq("task_num", instock.getTaskNum());
                        productTaskQueryWrapper.eq("receipt_num", instock.getReceiptNum());
                        List<ProductTask> productTasks = productTaskMapper.selectList(productTaskQueryWrapper);
                        ProductTask productTask = productTasks.get(0);
                        productTaskQuantity = productTask.getQuantity();

                        QueryWrapper<LatticeGoods> latticeGoodsQueryWrapper = new QueryWrapper<>();
                        latticeGoodsQueryWrapper.eq("instock_num", instock.getAcceptanceNum());
                        LatticeGoods warehouseLatticeGoods = latticeGoodsMapper.selectOne(latticeGoodsQueryWrapper);
                        //如果查询为null则代表此次为第一次入库
                        if (warehouseLatticeGoods != null) {
                            warehouseQuantity = warehouseLatticeGoods.getQuantity();
                        } else {
                            warehouseQuantity = 0;
                        }
                        if (quantity + warehouseQuantity >= productTaskQuantity) {
                            String receiptNum = instock.getReceiptNum();
                            String substringNum = receiptNum.substring(2);
                            completeRpt.setReceiptNum("WG" + substringNum);
                            completeRpt.setStatus("关闭");
                            completeRpt.setProductionOrderNum("MO" + substringNum);
                            completeRpt.setProductNum(instock.getGoodsCode());
                            completeRpt.setProductName(instock.getGoodsName());
                            completeRpt.setProductSpecification(instock.getSpecifications());
                            completeRpt.setProductUnit(productTask.getProductUnit());
                            completeRpt.setInstockQuantity(quantity + warehouseQuantity);
                            completeRpt.setQuantity(productTaskQuantity);
                            completeRpt.setEndQuantity(instock.getEndQuantity());
                            completeRpt.setInstockTime(instock.getInstockTime());
                            completeRpt.setScrapQuantity(instock.getScrapQuantity());
                            completeRpt.setReworkQuantity(instock.getReworkQuantity());
                            completeRpt.setProductSection(productTask.getProductSection());
                            completeRpt.setLocation(lattice.getLabel());
                            completeRpt.setCreateBy(iamUser.getRealname());
                            completeRptMapper.insert(completeRpt);
                        }
                    } else if (instock.getReceiptType().equals("FSCRK")) {
                        Receivement receivement = new Receivement();
                        QueryWrapper<PurchaseOrder> purchaseOrderQueryWrapper = new QueryWrapper<>();
                        purchaseOrderQueryWrapper.eq("receipt_num", instock.getReceiptNum());
                        purchaseOrderQueryWrapper.eq("row_num", instock.getReceiptNumRow());
                        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectOne(purchaseOrderQueryWrapper);
                        receivement.setBusinessDate(purchaseOrder.getBusinessDate());
                        receivement.setInstockDate(purchaseOrder.getCreateTime());
                        String receiptNum = instock.getReceiptNum();

                        String substringNum = receiptNum.substring(2);
                        receivement.setReceiptNum("RCV" + substringNum);
                        QueryWrapper<Receivement> receivementQueryWrapper = new QueryWrapper<>();
                        receivementQueryWrapper.eq("purchase_receipt_num", instock.getReceiptNum());
                        receivementQueryWrapper.eq("purchase_receipt_row", instock.getReceiptNumRow());
                        List<Receivement> receivementList = receivementMapper.selectList(receivementQueryWrapper);
                        int size = receivementList.size();
                        int row = 0;
                        for (int i = 0; i <= size; i++) {
                            row = row + 10;
                            receivement.setRowNum(row);
                        }
                        receivement.setProductNum(purchaseOrder.getProductNum());
                        receivement.setProductName(purchaseOrder.getProductName());
                        receivement.setProductSpecification(purchaseOrder.getSpecification());
                        receivement.setBuyReceiptNum(purchaseOrder.getSourceNum());
                        receivement.setBuyReceiptRow(purchaseOrder.getSourceNumRow());
                        receivement.setPurchaseReceiptNum(purchaseOrder.getReceiptNum());
                        receivement.setPurchaseReceiptRow(purchaseOrder.getRowNum());
                        receivement.setBusinessType(instock.getBusinessType());
                        receivement.setFactNum(purchaseOrder.getFactNum());
                        receivement.setFactReceiveNum(shelfIdAndGoodQuantityVO.getQuantity());
                        receivement.setUnit(instock.getUnit());
                        receivementMapper.insert(receivement);
                    } else {
                        ZhCn zhCn = new ZhCn();
                        QueryWrapper<ZhCn> zhCnQueryWrapper = new QueryWrapper<>();
                        zhCnQueryWrapper.eq("product_num", instock.getGoodsCode());
                        zhCnQueryWrapper.eq("location", instock.getLabel());
                        ZhCn zhCnOne = zhCnMapper.selectOne(zhCnQueryWrapper);
                        if (zhCnOne != null) {
                            Integer quantity = shelfIdAndGoodQuantityVO.getQuantity();
                            Integer zhCnNum = zhCnOne.getNowNum();
                            Integer nowNum = zhCnNum + quantity;
                            zhCnOne.setNowNum(nowNum);
                            //                    zhCn.setNowNum(shelfIdAndGoodQuantityVO.getQuantity() + zhCnOne.getNowNum());
                            zhCnMapper.updateById(zhCnOne);
                        } else {
                            zhCn.setNowNum(shelfIdAndGoodQuantityVO.getQuantity());
                            zhCn.setLocation(lattice.getLabel());
                            zhCn.setProductNum(instock.getGoodsCode());
                            zhCn.setProductName(instock.getGoodsName());
                            zhCn.setProductSpecification(instock.getSpecifications());
                            zhCn.setUnitName(instock.getUnit());
                            zhCnMapper.insert(zhCn);
                        }
                    }

                    if (latticeGoods == null) {
                        LatticeGoods latticeGoods1 = new LatticeGoods();
                        latticeGoods1.setGoodsId(instock.getGoodsId());
                        latticeGoods1.setWarehouseLatticeId(shelfIdAndGoodQuantityVO.getLatticeId());
                        latticeGoods1.setLable(lattice.getLabel());
                        latticeGoods1.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                        latticeGoods1.setGoodsCode(instock.getGoodsCode());
                        latticeGoods1.setGoodsName(instock.getGoodsName());
                        latticeGoods1.setGoodsSpecifications(instock.getSpecifications());
                        latticeGoods1.setTaskNum(instock.getTaskNum());
                        latticeGoods1.setInstockNum(instock.getAcceptanceNum());
                        latticeGoods1.setReceiptNum(instock.getReceiptNum());
                        latticeGoods1.setSourceNum(instock.getSourceNum());
                        latticeGoods1.setUnit(instock.getUnit());
                        latticeGoodsMapper.insert(latticeGoods1);
                    } else {
                        latticeGoods.setQuantity(latticeGoods.getQuantity() + shelfIdAndGoodQuantityVO.getQuantity());
                        latticeGoodsMapper.updateById(latticeGoods);
                    }
                }
            }


            //        instock.setCreateBy(iamUser.getRealname());
            //        instock.setUpdateBy(iamUser.getRealname());
            //        instockMapper.insert(instock);
            instock.setQuantity(allQuantity);
            instockMapper.updateById(instock);
            return JsonResult.OK("新增入库单成功");
        }
    }

    @Override
    public JsonResult getDetail(String acceptanceNum) {
        QueryWrapper<Instock> wrapper = new QueryWrapper<>();
        wrapper.eq("acceptance_num", acceptanceNum);
        Instock instockOne = instockMapper.selectOne(wrapper);
        InstockDetailVO instockDetailVO = new InstockDetailVO();
        if (instockOne != null) {
            BeanUtils.copyProperties(instockOne, instockDetailVO);
            List<ShelfIdAndGoodQuantityVO> shelfIdAndGoodQuantityVOS = new ArrayList<>();
            QueryWrapper<InstockLattice> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("instock_id", instockOne.getId());
            List<InstockLattice> instockLattices = instockLatticeMapper.selectList(wrapper1);
            for (InstockLattice instockLattice : instockLattices) {
                ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO = new ShelfIdAndGoodQuantityVO();
                shelfIdAndGoodQuantityVO.setId(instockLattice.getId());
                shelfIdAndGoodQuantityVO.setLatticeId(instockLattice.getWarehouseLatticeId());
                shelfIdAndGoodQuantityVO.setQuantity(instockLattice.getQuantity());
                shelfIdAndGoodQuantityVO.setLabel(instockLattice.getLabel());
                shelfIdAndGoodQuantityVOS.add(shelfIdAndGoodQuantityVO);
            }
            instockDetailVO.setShelfIdAndGoodsQuantityVOList(shelfIdAndGoodQuantityVOS);
        }
        return JsonResult.OK(instockDetailVO);
    }



    @Override
    public JsonResult unInsert(Instock instock) {
        if ("CXRK".equals(instockMapper.selectById(instock.getId()).getCancelType())) {
            return JsonResult.OK("该入库单已撤销，请勿重复提交撤销申请");
        }

        QueryWrapper<InstockRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("instock_id", instock.getId());
        List<InstockRecord> instockRecords = instockRecordMapper.selectList(wrapper);
        //判断撤销后商品的库存数量是否小于0
        for (InstockRecord instockRecord : instockRecords) {
            QueryWrapper<LatticeGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("warehouse_lattice_id", instockRecord.getWarehouseLatticeId());
            queryWrapper.eq("goods_id", instockRecord.getGoodsId());
            LatticeGoods latticeGoods = latticeGoodsMapper.selectOne(queryWrapper);
            if (latticeGoods.getQuantity() - instockRecord.getQuantity() < 0) {
                return JsonResult.FAIL_OPERATION("无法撤销，入库商品已出库，撤销后商品库存小于0 ");
            }
        }
        for (InstockRecord instockRecord : instockRecords) {
            //商品库存表更新
            QueryWrapper<LatticeGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("warehouse_lattice_id", instockRecord.getWarehouseLatticeId());
            queryWrapper.eq("goods_id", instock.getGoodsId());
            LatticeGoods latticeGoods = latticeGoodsMapper.selectOne(queryWrapper);
            if (latticeGoods.getQuantity() - instockRecord.getQuantity() == 0) {
                //删除库存
                latticeGoodsMapper.deleteByIdRealy(latticeGoods.getId());
                //查到该商品之前入库的货架格子
                Long warehouseLatticeId = instockRecord.getWarehouseLatticeId();
                Lattice lattice = latticeService.findById(warehouseLatticeId);
                //将货架格子状态改为空仓
                lattice.setStatus(0);
                latticeMapper.updateById(lattice);
            } else {
                latticeGoods.setQuantity(latticeGoods.getQuantity() - instockRecord.getQuantity());
                latticeGoodsMapper.updateById(latticeGoods);
            }
            //操作记录表新增撤销入库记录
            instockRecord.setId(null);
            instockRecord.setQuantity(0 - instockRecord.getQuantity());
            instockRecord.setType(instock.getCancelType());
            instockRecordMapper.insert(instockRecord);
        }
        //修改入库单表类型为撤销入库
        instockMapper.updateById(instock);
        //入库货格表记录删除
        instockLatticeMapper.deleteByInstockId(instock.getId());
        return JsonResult.OK("撤销成功");
    }

    //根据单据编号查询入库数量之和
    @Override
    public JsonResult getTotalQuantity(String receiptNum) {
        Integer total = 0;
        QueryWrapper<LatticeGoods> latticeGoodsQueryWrapper = new QueryWrapper<>();
        latticeGoodsQueryWrapper.eq("receipt_num", receiptNum);
        List<LatticeGoods> latticeGoodsList = latticeGoodsMapper.selectList(latticeGoodsQueryWrapper);
        for (LatticeGoods latticeGoods : latticeGoodsList) {
            total += latticeGoods.getQuantity();
        }
        return JsonResult.OK(total);
    }

    @Override
    public JsonResult updateInstock(InstockDTO instock) {
        Long currentUserId = IamSecurityUtils.getCurrentUserId();
        IamUser iamUser = iamUserMapper.selectById(currentUserId);
        //扫码时检查库位是否已被删除或是扫描出来的是其它环境的库位id
        if ( !CollectionUtils.isEmpty(instock.getShelfIdAndGoodsQuantityVOList().get(0).getShelfName())
                && instock.getShelfIdAndGoodsQuantityVOList().get(0).getLatticeId() !=null ){
            for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : instock.getShelfIdAndGoodsQuantityVOList()) {
                Lattice lattice = latticeService.findById(shelfIdAndGoodQuantityVO.getLatticeId());
                if (lattice == null) {
                    return JsonResult.FAIL_NOT_FOUND("二维码对应的库位存在异常");
                }
            }
        }
        //新增入库单
        if ( !CollectionUtils.isEmpty(instock.getShelfIdAndGoodsQuantityVOList().get(0).getShelfName())
                && instock.getShelfIdAndGoodsQuantityVOList().get(0).getLatticeId() !=null ){
            for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : instock.getShelfIdAndGoodsQuantityVOList()) {
                Lattice lattice = latticeService.findById(shelfIdAndGoodQuantityVO.getLatticeId());
                instock.setLabel(lattice.getLabel());
            }
        }



        Integer allQuantity = 0;
        if ( !CollectionUtils.isEmpty(instock.getShelfIdAndGoodsQuantityVOList().get(0).getShelfName())
                && instock.getShelfIdAndGoodsQuantityVOList().get(0).getLatticeId() !=null ){
            QueryWrapper<InstockLattice> instockLatticeQueryWrapper = new QueryWrapper<>();
            instockLatticeQueryWrapper.eq("instock_id",instock.getId());
            List<InstockLattice> instockLatticeList = instockLatticeMapper.selectList(instockLatticeQueryWrapper);
            for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : instock.getShelfIdAndGoodsQuantityVOList()) {
                allQuantity += shelfIdAndGoodQuantityVO.getQuantity();
                Lattice lattice = latticeService.findById(shelfIdAndGoodQuantityVO.getLatticeId());
                //货格如果是空仓就设置为空闲
                if (lattice.getStatus() == 2) {
                    lattice.setStatus(0);
                    latticeMapper.updateById(lattice);
                }
                //货架如果是空仓就设置为空闲
                Shelves shelves = shelvesMapper.selectById(lattice.getWarehouseShelvesId());
                if (shelves.getStatus() == 2) {
                    shelves.setStatus(0);
                    shelvesMapper.updateById(shelves);
                }
                //货区如果是空仓就设置为空闲
                Area area = areaMapper.selectById(shelves.getWarehouseAreaId());
                if (area.getStatus() == 2) {
                    area.setStatus(0);
                    areaMapper.updateById(area);
                }
                //仓库如果是空仓就设置为空闲
                Warehouse warehouse = warehouseMapper.selectById(area.getWarehouseId());
                if (warehouse.getStatus() == 2) {
                    warehouse.setStatus(0);
                    warehouseMapper.updateById(warehouse);
                }

                //更新入库表
                QueryWrapper<Instock> instockQueryWrapper = new QueryWrapper<>();
                instockQueryWrapper.eq("acceptance_num", instock.getAcceptanceNum());
                instock.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                instock.setUpdateBy(iamUser.getRealname());
                instockMapper.update(instock, instockQueryWrapper);

                //新增、修改入库货格表，删除在最后
                if (shelfIdAndGoodQuantityVO.getId() == null){
                    InstockLattice instockLattice = new InstockLattice();
                    instockLattice.setInstockId(instock.getId());
                    instockLattice.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                    instockLattice.setWarehouseLatticeId(shelfIdAndGoodQuantityVO.getLatticeId());
                    instockLattice.setLabel(lattice.getLabel());
                    instockLattice.setGoodsId(instock.getGoodsId());
                    instockLatticeMapper.insert(instockLattice);
                }else {
                    for (InstockLattice lattice1:instockLatticeList){
                        if ( shelfIdAndGoodQuantityVO.getId().equals(lattice1.getId())){
//                            lattice1.setWarehouseLatticeId(shelfIdAndGoodQuantityVO.getLatticeId());
//                            lattice1.setLabel(lattice.getLabel());
                            lattice1.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                            instockLatticeMapper.updateById(lattice1);
                        }
                    }
                }

                //入库操作记录
                QueryWrapper<InstockRecord> irqw = new QueryWrapper<>();
                irqw.eq("warehouse_lattice_id",shelfIdAndGoodQuantityVO.getLatticeId());
                irqw.eq("instock_id",instock.getId());
                InstockRecord instockRecord1 = instockRecordMapper.selectOne(irqw);

                if (instockRecord1 == null){
                    InstockRecord instockRecord = new InstockRecord();
                    instockRecord.setInstockId(instock.getId());
                    instockRecord.setWarehouseLatticeId(shelfIdAndGoodQuantityVO.getLatticeId());
                    instockRecord.setGoodsId(instock.getGoodsId());
                    instockRecord.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                    instockRecord.setType(instock.getReceiptType());
                    instockRecordMapper.insert(instockRecord);
                }else {
                    InstockRecord instockRecord = new InstockRecord();
                    instockRecord.setId(instockRecord1.getId());
                    instockRecord.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                    instockRecordMapper.updateById(instockRecord);
                }

                //货格关联商品表（库存数量表更新）
                QueryWrapper<LatticeGoods> wrapper = new QueryWrapper<>();
                wrapper.eq("goods_id", instock.getGoodsId());
                wrapper.eq("warehouse_lattice_id", shelfIdAndGoodQuantityVO.getLatticeId());
                LatticeGoods latticeGoods = latticeGoodsMapper.selectOne(wrapper);
                //查询商品表，得到商品名称、商品编号、商品规格
//            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
//            goodsQueryWrapper.eq("id", instock.getGoodsId());
//            Goods goods = goodsMapper.selectOne(goodsQueryWrapper);
                Integer productTaskQuantity = 0;
                Integer warehouseQuantity = 0;
                if (instock.getReceiptType().equals("SCRK")) {
                    CompleteRpt completeRpt = new CompleteRpt();

                    Integer quantity = shelfIdAndGoodQuantityVO.getQuantity();
                    QueryWrapper<ProductTask> productTaskQueryWrapper = new QueryWrapper<>();
                    productTaskQueryWrapper.eq("task_num", instock.getTaskNum());
                    productTaskQueryWrapper.eq("receipt_num", instock.getReceiptNum());
                    List<ProductTask> productTasks = productTaskMapper.selectList(productTaskQueryWrapper);
                    ProductTask productTask = productTasks.get(0);
                    productTaskQuantity = productTask.getQuantity();

                    QueryWrapper<LatticeGoods> latticeGoodsQueryWrapper = new QueryWrapper<>();
                    latticeGoodsQueryWrapper.eq("instock_num", instock.getAcceptanceNum());
                    List<LatticeGoods> warehouseLatticeGoods = latticeGoodsMapper.selectList(latticeGoodsQueryWrapper);
                    //如果查询为null则代表此次为第一次入库
                    if ( warehouseLatticeGoods != null && warehouseLatticeGoods.size() != 0 ) {
                        for ( LatticeGoods warehouseLatticeGood:warehouseLatticeGoods ){
                            warehouseQuantity = warehouseLatticeGood.getQuantity();
                        }
                    } else {
                        warehouseQuantity = 0;
                    }
                    if (quantity + warehouseQuantity >= productTaskQuantity) {
                        String receiptNum = instock.getReceiptNum();
                        String substringNum = receiptNum.substring(2);
                        completeRpt.setReceiptNum("WG" + substringNum);
                        completeRpt.setStatus("关闭");
                        completeRpt.setProductionOrderNum("MO" + substringNum);
                        completeRpt.setProductNum(instock.getGoodsCode());
                        completeRpt.setProductName(instock.getGoodsName());
                        completeRpt.setProductSpecification(instock.getSpecifications());
                        completeRpt.setProductUnit(productTask.getProductUnit());
                        completeRpt.setInstockQuantity(quantity + warehouseQuantity);
                        completeRpt.setQuantity(productTaskQuantity);
                        completeRpt.setEndQuantity(instock.getEndQuantity());
                        completeRpt.setInstockTime(instock.getInstockTime());
                        completeRpt.setScrapQuantity(instock.getScrapQuantity());
                        completeRpt.setReworkQuantity(instock.getReworkQuantity());
                        completeRpt.setProductSection(productTask.getProductSection());
                        completeRpt.setLocation(lattice.getLabel());
                        completeRpt.setCreateBy(iamUser.getRealname());
                        completeRptMapper.insert(completeRpt);
                    }
                } else if (instock.getReceiptType().equals("FSCRK")) {
                    Receivement receivement = new Receivement();
                    QueryWrapper<PurchaseOrder> purchaseOrderQueryWrapper = new QueryWrapper<>();
                    purchaseOrderQueryWrapper.eq("receipt_num", instock.getReceiptNum());
                    purchaseOrderQueryWrapper.eq("row_num", instock.getReceiptNumRow());
                    PurchaseOrder purchaseOrder = purchaseOrderMapper.selectOne(purchaseOrderQueryWrapper);
                    receivement.setBusinessDate(purchaseOrder.getBusinessDate());
                    receivement.setInstockDate(purchaseOrder.getCreateTime());
                    String receiptNum = instock.getReceiptNum();

                    String substringNum = receiptNum.substring(2);
                    receivement.setReceiptNum("RCV" + substringNum);
                    QueryWrapper<Receivement> receivementQueryWrapper = new QueryWrapper<>();
                    receivementQueryWrapper.eq("purchase_receipt_num", instock.getReceiptNum());
                    receivementQueryWrapper.eq("purchase_receipt_row", instock.getReceiptNumRow());
                    List<Receivement> receivementList = receivementMapper.selectList(receivementQueryWrapper);
                    int size = receivementList.size();
                    int row = 0;
                    for (int i = 0; i <= size; i++) {
                        row = row + 10;
                        receivement.setRowNum(row);
                    }
                    receivement.setProductNum(purchaseOrder.getProductNum());
                    receivement.setProductName(purchaseOrder.getProductName());
                    receivement.setProductSpecification(purchaseOrder.getSpecification());
                    receivement.setBuyReceiptNum(purchaseOrder.getSourceNum());
                    receivement.setBuyReceiptRow(purchaseOrder.getSourceNumRow());
                    receivement.setPurchaseReceiptNum(purchaseOrder.getReceiptNum());
                    receivement.setPurchaseReceiptRow(purchaseOrder.getRowNum());
                    receivement.setBusinessType(instock.getBusinessType());
                    receivement.setFactNum(purchaseOrder.getFactNum());
                    receivement.setFactReceiveNum(shelfIdAndGoodQuantityVO.getQuantity());
                    receivement.setUnit(instock.getUnit());
                    receivementMapper.insert(receivement);
                } else {
                    ZhCn zhCn = new ZhCn();
                    QueryWrapper<ZhCn> zhCnQueryWrapper = new QueryWrapper<>();
                    zhCnQueryWrapper.eq("product_num", instock.getGoodsCode());
                    zhCnQueryWrapper.eq("location", instock.getLabel());
                    ZhCn zhCnOne = zhCnMapper.selectOne(zhCnQueryWrapper);
                    if (zhCnOne != null) {
                        Integer quantity = shelfIdAndGoodQuantityVO.getQuantity();
                        Integer zhCnNum = zhCnOne.getNowNum();
                        Integer nowNum = zhCnNum + quantity;
                        zhCnOne.setNowNum(nowNum);
//                    zhCn.setNowNum(shelfIdAndGoodQuantityVO.getQuantity() + zhCnOne.getNowNum());
                        zhCnMapper.updateById(zhCnOne);
                    } else {
                        zhCn.setNowNum(shelfIdAndGoodQuantityVO.getQuantity());
                        zhCn.setLocation(lattice.getLabel());
                        zhCn.setProductNum(instock.getGoodsCode());
                        zhCn.setProductName(instock.getGoodsName());
                        zhCn.setProductSpecification(instock.getSpecifications());
                        zhCn.setUnitName(instock.getUnit());
                        zhCnMapper.insert(zhCn);
                    }
                }

                if (latticeGoods == null) {
                    LatticeGoods latticeGoods1 = new LatticeGoods();
                    latticeGoods1.setGoodsId(instock.getGoodsId());
                    latticeGoods1.setWarehouseLatticeId(shelfIdAndGoodQuantityVO.getLatticeId());
                    latticeGoods1.setLable(lattice.getLabel());
                    latticeGoods1.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                    latticeGoods1.setGoodsCode(instock.getGoodsCode());
                    latticeGoods1.setGoodsName(instock.getGoodsName());
                    latticeGoods1.setGoodsSpecifications(instock.getSpecifications());
                    latticeGoods1.setTaskNum(instock.getTaskNum());
                    latticeGoods1.setInstockNum(instock.getAcceptanceNum());
                    latticeGoods1.setReceiptNum(instock.getReceiptNum());
                    latticeGoods1.setSourceNum(instock.getSourceNum());
                    latticeGoods1.setUnit(instock.getUnit());
                    latticeGoodsMapper.insert(latticeGoods1);
                } else {
                    latticeGoods.setQuantity(shelfIdAndGoodQuantityVO.getQuantity());
                    latticeGoodsMapper.updateById(latticeGoods);
                }
            }
            //删除入库数据
            List<ShelfIdAndGoodQuantityVO> shelfIdAndGoodsQuantityVOList = instock.getShelfIdAndGoodsQuantityVOList();
            List<ShelfIdAndGoodQuantityVO> collect = shelfIdAndGoodsQuantityVOList.stream().filter(i -> i.getId() != null).collect(Collectors.toList());
            List<InstockLattice> oldList = instockLatticeList.stream()
                    .filter(instockLattice -> !collect.stream().anyMatch(s -> s.getId().equals(instockLattice.getId())))
                    .collect(Collectors.toList());
//            List<ShelfIdAndGoodQuantityVO> newList = shelfIdAndGoodsQuantityVOList.stream()
//                    .filter(shelfIdAndGoodQuantityVO -> !instockLatticeList.stream().anyMatch(i -> i.getId().equals(shelfIdAndGoodQuantityVO.getId())))
//                    .collect(Collectors.toList());

            for (InstockLattice a:oldList){
                instockLatticeMapper.deleteById(a.getId());
            }
        }

        instock.setQuantity(allQuantity);
        instockMapper.updateById(instock);
        return JsonResult.OK("修改入库单成功");
    }
}
